package com.zlq.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ToolUtil {
    /**
     * 纠正一下：ServletRequestAttributes 这个不能作为常量获取，因为每次request请求。
     * 都会建立新的RequestAttributes，如果使用static  final 修饰，会导致无法获取到新的 RequestAttributes。
     * 从而导致无法获取到session
     *
     * private static final ServletRequestAttributes SERVLET_REQUEST_ATTRS;
     * static {
     * SERVLET_REQUEST_ATTRS = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
     * }
     */

/*
    private static final String SESSION_USER_KEY = "userInfo";
    public static final String DEFAULT_INDEX_VIEW = "view/back/index";
    public static final String SUPER_USER_ID = "99999999999999990000000000000000";
*/

    /**
     * 获取最新的 ServletRequestAttributes
     * @return
     */
    private static ServletRequestAttributes getServletRequestAttrs() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        System.out.println("ToolUtil初始化了->" + requestAttributes);
        return requestAttributes;
    }

    /**
     * HttpServletRequest 获取
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return getServletRequestAttrs().getRequest();
    }

    /**
     * @return HttpSession
     */
    public static HttpSession getSession() {
        return getServletRequestAttrs().getRequest().getSession();
    }

    public static HttpServletResponse getResponse() {
        return getServletRequestAttrs().getResponse();
    }

    /**
     * 从Session中获取用户信息
     *
     * @return user
     */
/*    public static User getSessionUser() {
        return (User) getSession().getAttribute(SESSION_USER_KEY);
    }

    public static void setSessionUser(User user) {
        getSession().setAttribute(SESSION_USER_KEY, user);
    }*/

    public static String getBaseUrl() {
        HttpServletRequest request = getRequest();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
    }

/*    public static String uuid() {
        return StrUtil.removeAll(String.valueOf(UUID.randomUUID()), "-").toUpperCase();
    }*/
}
